Switch Function

Course- R Programming >

Like the switch statements in other programming languages, R has a similar construct in the form of switch() function.

Syntax of switch() function

switch (statement, list)

Here, the statement is evaluated and based on this value, the corresponding item in the list is returned.

Example of switch() function

If the value evaluated is a number, that item of the list is returned.

> switch(2,"red","green","blue")
[1] "green"

> switch(1,"red","green","blue")
[1] "red"

 

 
 

In the above example, "red","green","blue" form a three item list. So, the switch() function returns the corresponding item to the numeric value evaluated. But if the numeric value is out of range (greater than the number of items in the list or smaller than 1), then, NULL is returned.

> x <- switch(4,"red","green","blue")
> x
NULL

> x <- switch(0,"red","green","blue")
> x
NULL

The result of the statement can be a string as well. In this case, the matching named item's value is returned.

> switch("color", "color"="red", "shape"="square", "length"=5)
[1] "red"

> switch("length", "color"="red", "shape"="square", "length"=5)
[1] 5